package org.wjk.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.impl.DefaultClaims;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.wjk.props.JwtProperties;

import java.util.Date;

@Component
@Slf4j
@RequiredArgsConstructor
public class JwtTokenUtils {
    @Getter
    private final JwtProperties props;

    /*构建token*/
    public String getJwtToken(String username) {
        return Jwts.builder().setClaims(getClaims(username))
                .signWith(SignatureAlgorithm.HS512, props.getSecret())
                .compact();
    }

    private Claims getClaims(String username) {
        Claims claims = new DefaultClaims();
        claims.setSubject(username);
        claims.setExpiration(new Date(System.currentTimeMillis() + props.getExpired()));
        return claims;
    }

    /*解析token*/
    public String resolverJwtToken(String token) throws Exception {
        return (Jwts.parser().setSigningKey(props.getSecret())
                .parseClaimsJws(token)
                .getBody()
        ).getSubject();
    }
}
